package com.test;

import com.study.LikeApp;
import com.study.utils.RedisLock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 模拟秒杀
 */

@SpringBootTest(classes = LikeApp.class)
@RunWith(SpringRunner.class)
public class SecKillServiceDemo {

    @Autowired
    RedisLock redisLock;

    //超时时间10s
    private static final int TIMEOUT = 10 * 1000;

    @Test
    public void testSecKill() throws Exception {
        String productId = "prod";
        long time = System.currentTimeMillis() + TIMEOUT;
        //加锁
        if (!redisLock.lock(productId, String.valueOf(time))){
            throw new Exception("人太多了，等会儿再试吧~");
        }

        System.out.println("secKill");
        //具体的秒杀逻辑

        //解锁
        redisLock.unlock(productId, String.valueOf(time));
    }
}
